package com.lechuang.mq.client;

import com.lechuang.common.constant.BaseConstant;
import lombok.extern.log4j.Log4j2;
import org.slf4j.MDC;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

/**
 * <p>
 *     消息队列客户端
 * </p>
 * @author liaoningbo
 * @since 2023/12/25
 */
@Log4j2
@Configuration
public class RabbitMqClient {
    private final RabbitTemplate rabbitTemplate;

    @Autowired
    public RabbitMqClient(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * <p>
     *     发送延迟消息
     * </p>
     * @author liaoningbo
     * @since 2024/1/8
     */
    public void sendDelayMessage(String exchangeName, String routingKey, Object msg, Integer expiration) {
        log.info("发送消息到MQ，入参打印：exchangeName->{},routingKey->{},msg->{},expiration->{}",exchangeName,routingKey,msg,expiration);
        //发消息前先获取到traceId，然后作为CorrelationData的id
        String traceId = MDC.get(BaseConstant.TRACE_ID);
        rabbitTemplate.convertAndSend(exchangeName,routingKey, msg,message->{
            message.getMessageProperties().setHeader(BaseConstant.TRACE_ID, traceId);
            if(null != expiration){
                message.getMessageProperties().setHeader("x-delay", expiration);
            }
            return message;
        },new CorrelationData(traceId));
    }

    /**
     * <p>
     *     发送普通消息
     * </p>
     * @author liaoningbo
     * @since 2024/1/8
     */
    public void sendMessage(String exchangeName, String routingKey, Object msg) {
        log.info("发送消息到MQ，入参打印：exchangeName->{},routingKey->{},msg->{}",exchangeName,routingKey,msg);
        //发消息前先获取到traceId，然后作为CorrelationData的id
        String traceId = MDC.get(BaseConstant.TRACE_ID);
        rabbitTemplate.convertAndSend(exchangeName,routingKey, msg, message->{
            message.getMessageProperties().setHeader(BaseConstant.TRACE_ID, traceId);
            return message;
        },new CorrelationData(traceId));
    }
}
